// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

import { AcceptInvite, NoticeLeaveInvite, NoticeUserInviteStatus, PairRequest } from "../bean/GameBean";
import { GlobalBean } from "../bean/GlobalBean";
import { GameMgr } from "../common/GameMgr";
import { MessageId } from "../net/MessageId";
import { WebSocketManager } from "../net/WebSocketManager";
import { WebSocketToolState } from "../net/WebSocketTool";
import ToastController from "../ToastController";
import { AudioManager } from "../util/AudioManager";
import HallParentController from "./HallParentController";
import InfoDialogController from "./InfoDialogController";
import KickOutDialogController from "./KickOutDialogController";
import LeaveDialogController from "./LeaveDialogController";
import MatchParentController from "./MatchParentController";
import SettingDialogController from "./SettingDialogController";

const { ccclass, property } = cc._decorator;


export enum HallOrMatch {
    HALL_PARENT,    //大厅页面
    MATCH_PARENT,   //匹配页面
}

@ccclass
export default class HallPageController extends cc.Component {

    @property(cc.Node)
    hallParentNode: cc.Node = null;
    @property(cc.Node)
    matchParentNode: cc.Node = null;
    @property(InfoDialogController)
    infoDialogController: InfoDialogController = null //道具简介弹窗
    @property(LeaveDialogController)
    leaveDialogController: LeaveDialogController = null // 退出游戏弹窗
    @property(SettingDialogController)
    settingDialogController: SettingDialogController = null //设置弹窗
    @property(KickOutDialogController)
    kickOutDialogController: KickOutDialogController = null //踢出用户的 dialog
    @property(ToastController)
    toastController: ToastController = null  //toast 的布局

    hallOrMatch: HallOrMatch = null

    hallParentController: HallParentController
    matchParentController: MatchParentController

    // 防并发点击：开始匹配/创建房间过程中避免重复触发
    private isStarting: boolean = false;
    
    // 🎯 防止弹窗带入游戏：开始游戏后短时间内禁止点击其他按钮
    private isButtonsDisabled: boolean = false;

    onLoad() {
        this.hallParentController = this.hallParentNode.getComponent(HallParentController)
        this.matchParentController = this.matchParentNode.getComponent(MatchParentController)

    }

    protected onEnable(): void {
        AudioManager.playBgm()
        this.setHallOrMatch(HallOrMatch.HALL_PARENT)

    }

    protected onDisable(): void {
        // 清理定时器，防止内存泄漏
        this.unscheduleAllCallbacks();
        // 重置按钮禁用状态
        this.isButtonsDisabled = false;
    }

    start() {

        this.hallParentController.setClick(() => {
            //返回键的回调
            if (this.isButtonsDisabled) {
                
                return;
            }
            this.leaveDialogController.show(0,()=>{})
        }, () => {
            //info 的回调
            if (this.isButtonsDisabled) {
                
                return;
            }
            this.infoDialogController.show(()=>{})
        }, () => {
            //设置键的回调
            if (this.isButtonsDisabled) {
               
                return;
            }
            this.settingDialogController.show(()=>{})
        }, () => {
            //start 按钮点击
            if (this.isButtonsDisabled) {
              
                return;
            }
            this.startOrCreate(MessageId.MsgTypePairRequest)

        }, () => {
            //create 点击创建房间
            if (this.isButtonsDisabled) {
             
                return;
            }
            this.startOrCreate(MessageId.MsgTypeCreateInvite)

        }, (userId: string, nickname: string) => {
            //点击创建房间内的 点击玩家头像 弹出的踢出房间弹窗
            if (this.isButtonsDisabled) {
              
                return;
            }
            this.kickOutDialogController.show(userId, nickname)
        })

        this.matchParentController.setClick(() => {
            //匹配页面的返回键的回调
            WebSocketManager.GetInstance().sendMsg(MessageId.MsgTypeCancelPair, {});

        })

    }
    updateGold() {
        this.hallParentController.updateGold()
    }

    //开始匹配 或者创建房间
    startOrCreate(msgId: MessageId) {

        //判断是否链接成功，并且还得有登录成功的数据返回 ，不成功的话就不允许执行下面的操作
        if (WebSocketManager.GetInstance().webState != WebSocketToolState.Connected || GlobalBean.GetInstance().loginData == null) {
            // 若网络/登录不满足，恢复点击状态
            return;
        }

        // 🎯 关闭所有可能打开的弹窗，防止带入到游戏页面
        this.closeAllDialogs();

        // 🎯 启用按钮禁用机制，防止在开始游戏后立即点击其他按钮
        this.disableButtonsTemporarily();

        //点击 快速开始游戏 start 的回调
        let pairRequest: PairRequest = {
            playerNum: GlobalBean.GetInstance().players,
            fee: GlobalBean.GetInstance().ticketsNum,
        }
        //发送请求开始游戏的消息
        WebSocketManager.GetInstance().sendMsg(msgId, pairRequest);
    }

    /**
     * 临时禁用所有按钮0.5秒，防止开始游戏后立即点击其他按钮导致弹窗带入游戏
     */
    private disableButtonsTemporarily(): void {
        if (this.isButtonsDisabled) {
            return; // 已经在禁用状态，避免重复设置
        }

        this.isButtonsDisabled = true;
       

        // 0.5秒后恢复按钮点击
        this.scheduleOnce(() => {
            this.isButtonsDisabled = false;
           
        }, 0.5);
    }

    /**
     * 关闭所有可能打开的弹窗，防止带入到游戏页面
     */
    private closeAllDialogs(): void {
        try {
            // 关闭规则/道具简介弹窗
            if (this.infoDialogController && this.infoDialogController.node && this.infoDialogController.node.active) {
                this.infoDialogController.hide();
                
            }

            // 关闭设置弹窗
            if (this.settingDialogController && this.settingDialogController.node && this.settingDialogController.node.active) {
                this.settingDialogController.hide();
                
            }

            // 关闭退出游戏弹窗
            if (this.leaveDialogController && this.leaveDialogController.node && this.leaveDialogController.node.active) {
                this.leaveDialogController.hide();
             
            }

            // 关闭踢出用户弹窗
            if (this.kickOutDialogController && this.kickOutDialogController.node && this.kickOutDialogController.node.active) {
                this.kickOutDialogController.hide();
                
            }

            
        } catch (error) {
            console.error("❌ 关闭弹窗时出错:", error);
        }
    }

    //设置是大厅 还是匹配页面
    setHallOrMatch(hallOrMatch: HallOrMatch) {
        if (this.hallOrMatch === hallOrMatch) {
            return
        }
        this.hallOrMatch = hallOrMatch
        this.hallParentNode.active = false
        this.matchParentNode.active = false
        switch (hallOrMatch) {
            case HallOrMatch.HALL_PARENT:
                this.hallParentNode.active = true
                break;
            case HallOrMatch.MATCH_PARENT:
                this.matchParentNode.active = true
                break;
        }
    }


    LoginSuccess() {
        //登录成功后 执行的操作
        GameMgr.Console.Log("登录成功")
        let loginData = GlobalBean.GetInstance().loginData
        if (loginData) {
            if (loginData.roomId > 0) { //正在游戏中
                WebSocketManager.GetInstance().sendMsg(MessageId.MsgTypeEnterRoom, {})//重连进来的 玩家请求进入房间
            }
            else if (loginData.inviteCode > 0) {//正在私人房间
                WebSocketManager.GetInstance().sendMsg(MessageId.MsgTypeAcceptInvite, { 'inviteCode': Number(loginData.inviteCode) })
            } else {
                //房间已经解散了  但是我还留在私人房间
                this.hallParentController.exitTheRoom()
            }
            //重连的时候 被遗留在匹配页面的话 就回到大厅
            if (loginData.roomId == 0 && loginData.inviteCode == 0 && this.hallOrMatch == HallOrMatch.MATCH_PARENT) {
                this.setHallOrMatch(HallOrMatch.HALL_PARENT)
            }
        }
        this.setFees()
    }

    //设置接受邀请成功
    setAcceptInvite(acceptInvite: AcceptInvite) {
        this.hallParentController.setAcceptInvite(acceptInvite)
    }
    //离开房间
    leaveRoom(noticeLeaveInvite: NoticeLeaveInvite) {
        this.hallParentController.leaveRoom(noticeLeaveInvite)
    }


    //设置门票
    setFees() {
        this.hallParentController.setFees()
    }

    //初始化 match 页面
    createMatchView() {
        this.matchParentController.createMatchView()
    }
    //设置匹配数据
    setGameData() {
        this.matchParentController.setGameData()
    }

    //进入私人房间
    joinCreateRoom(){
        this.hallParentController.joinCreateRoom()
    }
    //房间号无效
    joinError() {
        this.hallParentController.joinError()
    }
    //准备 取消准备
    setReadyState(noticeUserInviteStatus: NoticeUserInviteStatus) {
        if (this.hallParentController) {
            this.hallParentController.setReadyState(noticeUserInviteStatus)
        }

    }

    // update (dt) {}
}
